<?php

/**
 * Classe prenant en charge les requetes SQL de type [SELECT]
 *
 * @category   McCube
 * @package    Db
 * @author     Leiha Sellier <leiha.sellier@gmail.com>
 * @license    http://creativecommons.org/licenses/by/3.0/  CC BY 3.0
 * @link       http://code.google.com/p/mechanics-cubes/
 * @see        http://www.php.net/manual/book.pdo.php
 */
class McCube_Db_Query_Select extends McCube_Db_Query{

    protected $_joinTo       = '';
    protected $_groupBy      = '';
    protected $_fields    = '';
    public $PDOStatement     = null;

    protected $_fetchMode = array();

    public function exec(&$fetchMode=PDO::FETCH_ASSOC){
        return new McCube_Db_Result(
              $this->_database->query($this->build(), $fetchMode)
            , $this
        );
    }

    public function build(){
        $q  = 'SELECT '.$this->_fields
            .' FROM '.$this->_table
        ;

        if(!empty($this->_joinTo))
           $q .= ' '.$this->_joinTo;

        if(!empty($this->_where))
           $q .= ' WHERE '.$this->_where;

        if(!empty($this->_orderBy))
            $q .= ' ORDER BY '.$this->_orderBy;

        if(!empty($this->_having))
            $q .= ' HAVING '.$this->_having;

        if(!empty($this->_groupBy))
            $q .= ' GROUP BY '.$this->_groupBy;

        if(!empty($this->_limit))
            $q .= ' LIMIT '.$this->_limit;

        return $q.';';
    }

    /** */
    public function buildSqlByObject($sqlParams){
        if(isset($sqlParams->orderBy)){
            foreach($sqlParams->orderBy as $field=>$order){
                $this->orderBy($field, $order);
            }
        }
        return $this;
    }

    public function fields($fields){
        if(!empty($this->_fields))
            $this->_fields .= ',';

        $this->_fields .= $fields;
        return $this;

    }

	public function joinTo($tableToJoin='', $where='', $type='INNER JOIN'){
        //if(!empty($this->_joinTo))
            //$this->_joinTo .= ' AND ';

        $this->_joinTo .= ' '.$type.' '.$tableToJoin.' ON '.$where;
        return $this;
    }

    public function groupBy($groupBy){
        if(!empty($this->_groupBy))
            $this->_groupBy .= ' , ';

        $this->_groupBy .= $groupBy;
        return $this;
    }

    public function having($expression, $value=null, $valueType=PDO::PARAM_STR){
        $this->_having .= $this->__($expression, $value, $valueType);
        return $this;
    }

    public function andHaving($expression, $value=null, $valueType=PDO::PARAM_STR){
        $this->_having .= ' AND ('.$this->__($expression, $value, $valueType).')';
        return $this;
    }

    public function orHaving($expression, $value=null, $valueType=PDO::PARAM_STR){
        $this->_having .= ' OR ('.$this->__($expression, $value, $valueType).')';
        return $this;
    }

}